﻿using ControlzEx.Theming;
using ICSharpCode.AvalonEdit;
using MahApps.Metro.Controls;
using Serilog;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using VideoTools.Commands;
using VideoTools.Help;
using VideoTools.Tasks;
using VideoTools.vo;

namespace VideoTools
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        public static MainWindow Instance;
        private static readonly string logFileStart = "log";
        private static readonly string imageFileStart = "Snipaste";
        private static BrushConverter BrushConverter = new BrushConverter();

        public MainWindow()
        {
            InitializeComponent();
            Instance = this;
            System.Windows.Application.Current.MainWindow = this;
            string defaultPage = AppConfig.Instance.DefaultPage;
            //if (defaultPage != null && defaultPage.Length > 0)
            //{
            //    MainFrame.Navigate(new Uri(defaultPage, UriKind.RelativeOrAbsolute));
            //}
            string defaultTitle = AppConfig.Instance.DefaultTitle;
            if (defaultTitle != null && defaultTitle.Length > 0)
            {
                this.Title = defaultTitle;
            }
            string AccentName = AppConfig.Instance.AccentName;
            string Background = AppConfig.Instance.BackgroundColor;
            string rootPath = Directory.GetCurrentDirectory();
            DirectoryInfo root = new DirectoryInfo(rootPath);
            FileInfo[] files = root.GetFiles();
            if (AccentName != null && AccentName.Length > 0)
            {
                ThemeManager.Current.ChangeThemeColorScheme(
                    System.Windows.Application.Current,
                    AccentName
                );
            }
            if (Background != null && Background.Length > 0)
            {
                SolidColorBrush brush = (SolidColorBrush)BrushConverter.ConvertFromString(Background);
                AppManager.Instance.BackgroundColor = brush;
            }

            foreach (FileInfo f in files)
            {
                string fName = f.Name;
                if (fName.StartsWith(imageFileStart) || fName.StartsWith(logFileStart))
                {
                    File.Delete("./" + fName);
                }
            }

            foreach (AccentColorMenuData data in ThemeManager.Current.Themes
                                  .GroupBy(x => x.ColorScheme)
                                  .OrderBy(a => a.Key)
                                  .Select(a => new AccentColorMenuData { Name = a.Key, ColorBrush = a.First().ShowcaseBrush })
                                  .ToList())
            {
                MenuItem item = new MenuItem();
                item.Header = data.Name;
                item.Tag = data.Name;
                item.Cursor = System.Windows.Input.Cursors.Hand;
                item.Command = MainWindowCommands.Instance.ChangeAccentColorCommand;
                item.CommandParameter = data.Name;
                item.Foreground = data.ColorBrush;
                item.Icon = new System.Windows.Shapes.Path
                {
                    Data = Geometry.Parse("M512 106.667c-47.040 0-85.333 38.293-85.333 85.333s38.293 85.333 85.333 85.333c47.040 0 85.333-38.293 85.333-85.333s-38.293-85.333-85.333-85.333zM511.957 192.124l-42.624-0.124h42.667c0 0.043 0 0.085-0.043 0.124z"),
                    Fill = data.ColorBrush,
                    Width = 21,
                    Height = 21,
                    Stretch = Stretch.Uniform,
                    Cursor = System.Windows.Input.Cursors.Hand,
                    UseLayoutRounding = true,

                };
                ThemeAccentMenuItem.Items.Add(item);
            }

            string[] backgrounds = new string[] { "AliceBlue", "AntiqueWhite", "OldLace", "Azure", "Lavender", "LightCyan", "PaleTurquoise", "SkyBlue"};
            foreach (string bg in backgrounds)
            {
                SolidColorBrush brush = (SolidColorBrush)BrushConverter.ConvertFromString(bg);
                ThemeColor tc = new ThemeColor(bg, brush);
                AppManager.Instance.BackgroundColors.Add(tc);
                MenuItem item = new MenuItem();
                item.Header = bg;
                item.Tag = bg;
                item.Cursor = System.Windows.Input.Cursors.Hand;
                item.Command = MainWindowCommands.Instance.ChangeBackgroundCommand;
                item.CommandParameter = bg;
                item.Foreground = brush;
                item.Icon = new System.Windows.Shapes.Path
                {
                    Data = Geometry.Parse("M512 106.667c-47.040 0-85.333 38.293-85.333 85.333s38.293 85.333 85.333 85.333c47.040 0 85.333-38.293 85.333-85.333s-38.293-85.333-85.333-85.333zM511.957 192.124l-42.624-0.124h42.667c0 0.043 0 0.085-0.043 0.124z"),
                    Fill = brush,
                    Width = 21,
                    Height = 21,
                    Stretch = Stretch.Uniform,
                    Cursor = System.Windows.Input.Cursors.Hand,
                    UseLayoutRounding = true,

                };
                ThemeBackgroundMenuItem.Items.Add(item);
            }

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.With<LogCallerEnricher>()
                .WriteTo.File(path:"./log.txt", rollingInterval: RollingInterval.Month,outputTemplate: "{Timestamp:HH:mm:ss} [{Level}] {Caller} (Line:{LineNumber}) {Message}{NewLine}{Exception}"

                )
                .CreateLogger();
            Log.Information("启动了");
        }

        private void Min_Click(object sender, RoutedEventArgs e)
        {
            base.WindowState = WindowState.Minimized;
        }

        public Frame MainWindowFrame()
        {
            return MainFrame;
        }
        public MetroProgressBar MetroProgressBar()
        {
            return MainWindowProgressBar;
        }
        public MenuItem JianYingAudioMenuItem()
        {
            return ExportJianYingAudioMenuItem;
        }

        public MenuItem JianYingVideoMenuItem()
        {
            return ExportJianYingVideoMenuItem;
        }

        public MenuItem JianYingVideoRenameMenuItem()
        {
            return ExportJianYingVideoRenameMenuItem;
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
            AppManager.EXIT_APP = true;
            DownloadM3u8TaskQueueManager.Instance.StopAllTasks();
            base.Close();
        }

        public static T FindVisualParent<T>(DependencyObject child)
            where T : DependencyObject
        {
            while (child != null && !(child is T))
            {
                try
                {
                    child = VisualTreeHelper.GetParent(child);
                }catch (Exception e)
                {
                    if(e.Message.Contains("不是 Visual 或 Visual3D"))
                    {
                        //由于System.Windows.Documents.Run
                        return child as T;
                    }
                }
            }
            return child as T;
        }

        private void MetroWindow_PreviewMouseMove(
            object sender,
            System.Windows.Input.MouseEventArgs e
        )
        {
            if (
                e.MouseDevice.DirectlyOver is ScrollViewer
                || e.MouseDevice.DirectlyOver is ScrollBar
                || e.MouseDevice.DirectlyOver is Canvas
                || e.MouseDevice.DirectlyOver is TextEditor

            )
            {
                return;
            }
            if (e.OriginalSource is DependencyObject source)
            {
                if(FindVisualParent<System.Windows.Controls.ListView>(source) != null 
                    || FindVisualParent<System.Windows.Controls.ListBox>(source) != null
                    || FindVisualParent<System.Windows.Controls.TextBox>(source) != null
                    || FindVisualParent<System.Windows.Controls.TextBlock>(source) != null
                    || FindVisualParent<System.Windows.Controls.RichTextBox>(source) != null
                    || FindVisualParent<System.Windows.Controls.Canvas>(source) != null
                    || FindVisualParent<System.Windows.Controls.ComboBox>(source) != null
                    || FindVisualParent<TextEditor>(source) != null
                    
                    )
                // 不处理这些控件的事件
                return;
            }
            e.Handled = true;
            
        }

        private void SettingsFlyout_IsOpenChanged(object sender, RoutedEventArgs e)
        {
            Flyout flyout = (Flyout)sender;
            AppManager.Instance.SettingsFlyoutOpened = flyout.IsOpen; 
        }
        
        private void BackgroundComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            System.Windows.Controls.ComboBox comboBox = (System.Windows.Controls.ComboBox)sender;
            ThemeColor selectedItem = (ThemeColor)comboBox.SelectedItem;
            MainWindowCommands.Instance.ChangeBackgroundCommand.Execute(selectedItem.Key);
        }
        private void AccentComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            System.Windows.Controls.ComboBox comboBox = (System.Windows.Controls.ComboBox)sender;
            AccentColorMenuData selectedItem = (AccentColorMenuData)comboBox.SelectedItem;
            MainWindowCommands.Instance.ChangeAccentColorCommand.Execute(selectedItem.Name);
            SolidColorBrush oldbackground = AppManager.Instance.BackgroundColor;
            SolidColorBrush background = (SolidColorBrush)new SolidColorBrush(Colors.Transparent) ;
            AppManager.Instance.BackgroundColor = background;
            AppManager.Instance.BackgroundColor = oldbackground;
        }

        private void NotifycationMenuPopup_Closed(object sender, EventArgs e)
        {
            MainWindowCommands.Instance.Notifycations = new System.Collections.ObjectModel.ObservableCollection<string>();
        }

    }
}
